package com.itjob.scott.lesson04.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import com.deep.json.core.JsonParser;

public class ApplicationContext {
	
	
	private Map<String, Object> context = new HashMap<String, Object>();
	
	private JsonParser jp = new JsonParser();
	
	public ApplicationContext(){
		
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ApplicationContext(String fileName){
		Map<String, Object> bns = null;
		try {
			ResourceBundle bundle = ResourceBundle.getBundle(fileName);
			bns =(Map<String, Object>) jp.fromJson(bundle.getString("bns"));
			
			List beans =	(List) bns.get("beans");
			
			for (Object bean : beans) {
				//System.out.println(object);
				Map<String, Object> beanMap = (Map<String, Object>) bean;
				
				String id  = (String) beanMap.get("id");
				String clazz= (String) beanMap.get("clazz");
				
				//com.itjob.scott.lesson04.action.HelloAction
				Object beanInstance = Class.forName(clazz).newInstance();
				
				//放入到context中
				context.put(id, beanInstance);
				
				//{id=action, clazz=com.itjob.scott.lesson04.action.HelloAction, property={name=animalDao, ref=cat}}
				Object property = beanMap.get("property");
				if(null != property ){
					//说明要注入
					Map<String, Object> p = (Map<String, Object>) property;
					String name =(String) p.get("name"); //animalDao  
					String setter = "set" +name.substring(0, 1).toUpperCase()+ name.substring(1);
					System.out.println("setter="+setter);
					Method method = getMethod(beanInstance.getClass(), setter);  // animalDao 变成  setAnimalDao
					System.out.println("method="+method);
					
					String ref =(String) p.get("ref"); //ref=cat
					Object dao= context.get(ref);
					if(null != dao){
						method.invoke(beanInstance, dao);  //HelloAction.setAnimalDao(AnimalDao animalDao)
					}
					
				}
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private Method getMethod(Class<?> clazz, String name){
		Method[] methods = clazz.getDeclaredMethods();
		for (Method method : methods) {
			if(method.getName().equals(name)){
				return method;
			}
		}
		return null;
	}
	
	public Object getBean(String beanId){
		return context.get(beanId);
	}
	
	@SuppressWarnings("unused")
	public static void main(String[] args) {
		ApplicationContext context = new ApplicationContext();
	}

}
